package com.mark.app.chat;

import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedNioFile;

import java.io.RandomAccessFile;

/**
 * Created by WEIBIN521 on 2016/3/7.
 */
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private final String wsUrl;

    public HttpRequestHandler(String wsUrl) {
        super();
        this.wsUrl = wsUrl;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        if(wsUrl.equalsIgnoreCase(request.uri())){
            ctx.fireChannelRead(request.retain());
        }else{
            if(HttpUtil.is100ContinueExpected(request)){
                FullHttpResponse req = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.CONTINUE);
                ctx.writeAndFlush(req);
            }

            RandomAccessFile file = new RandomAccessFile(HttpRequestHandler.class.getResource("/").getPath()+"index.html","r");
            HttpResponse req = new DefaultHttpResponse(request.protocolVersion(),HttpResponseStatus.OK);
            req.headers().set(HttpHeaders.Names.CONTENT_TYPE,"text/html;charset=UTF-8");

            boolean isKeepAlive = HttpHeaders.isKeepAlive(req);

            if(isKeepAlive){
                req.headers().set(HttpHeaders.Names.CONTENT_LENGTH,file.length());
                req.headers().set(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.KEEP_ALIVE);
            }

            ctx.write(req);

            if(ctx.pipeline().get(SslHandler.class) == null){
                ctx.write(new DefaultFileRegion(file.getChannel(),0,file.length()));
            }else{
                ctx.write(new ChunkedNioFile(file.getChannel()));
            }


            ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

            if(!isKeepAlive){
                future.addListener(ChannelFutureListener.CLOSE);
            }

            file.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }
}
